package com.scalar.chiptrack.adaptor.ubicom.spil;

import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.users.VendorAdaptor;
import com.scalar.chiptrack.users.dao.AdaptorSetUpDAO;
import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.ScalarException;
import com.enterprisedt.net.ftp.FTPClient;
import com.enterprisedt.net.ftp.FTPTransferType;
import com.enterprisedt.net.ftp.FTPConnectMode;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;

/**
 * Created by IntelliJ IDEA.
 * User: Sudhakar
 * Date: Sep 20, 2007
 * Time: 8:04:20 PM
 */
public class SPILFTPSortAdaptor  extends JobHandler implements AdaptorConstants
{


   private static final int    PORT                 = 21;
   private static final String FTP_HOST             = "ftp2.hs.spil.com.tw";
   private static final String FILE_EXTN            = ".txt";
   private static final String SORT_DIR_IP5K        = "/WS_Data_IP5k/";
   private static final String SORT_DIR_IP3K        = "/WS_Data_IP3k/";
   public static final String ADAPTOR_NAME1          = "SPIL_SORT_BIN_IP5k";
   public static final String ADAPTOR_NAME2         = "SPIL_SORT_BIN_IP3k";
   public static final String FILE_NAME_SORT_WIP    = "spil_sort_wip";

   private Logger m_adaptorLogger      = null;
   private String m_dataOutputDir      = null;
   private String m_username           = null;
   private String m_password           = null;
   private int    m_adaptor_id1         = -1;
   private int    m_adaptor_id2        = -1;
   private String fileDate1            = null;
   private String fileDate2            = null;

   public SPILFTPSortAdaptor() throws Exception
   {
        try
        {
            VendorAdaptor vendorAdaptor = AdaptorSetUpDAO.getVendorAdaptorDetailsByVendorNameAndLocation(VENDOR_NAME_SPIL, WIP_TYPE_SORT);

            m_username = vendorAdaptor.getUserId();
            m_password = vendorAdaptor.getPassWord();
            m_dataOutputDir = vendorAdaptor.getOutPutDirectory();

            if (m_dataOutputDir != null)
            {
                if (m_dataOutputDir.endsWith("/") || m_dataOutputDir.endsWith("\\"))
                {
                    m_dataOutputDir = m_dataOutputDir + m_username;
                }
                else
                {
                    m_dataOutputDir = m_dataOutputDir + "/" + m_username;
                }
            }

            AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
            m_adaptorLogger = AdaptorUtils.getAdaptorLogger( m_dataOutputDir, VENDOR_NAME_SPIL );
            AdaptorUtils.setLogger( m_adaptorLogger );
        }
        catch (ScalarException se)
        {
            log("ERROR!! ERROR!! ERROR!! Exception while loading SPIL Adaptor Username, Password details from database, Exception: " + se);
            throw se;
        }
   }
   //Main Method
   public static void main(String[] args) throws Exception
   {
       new SPILFTPSortAdaptor().execute();
   }
    /**
    *
    * @throws Exception
    */
   public void execute() throws Exception
   {
       java.util.Date begDate1 = null;
       java.util.Date begDate2 = null;
       try
       {
            //Getting the last Run Adaptor file Date ( As we are Inserting in the new Adaptor run info in the Starting itself)
           fileDate1   = AdaptorRunInfo.getAdaptorLastParsedFileDate( ADAPTOR_NAME1 );
           fileDate2   = AdaptorRunInfo.getAdaptorLastParsedFileDate( ADAPTOR_NAME2 );
           //When File Date is NULL Setting the File Date Back to 4 Days From Current Date
           if ( fileDate1 == null )
           {
               Calendar cal = Calendar.getInstance();
               cal.add( Calendar.DAY_OF_MONTH, -150 );
               begDate1 = cal.getTime();
               fileDate1 = StringUtils.formatDateToString( begDate1, "MM/dd/yyyy");
           }
           if ( fileDate2 == null )
           {
               Calendar cal = Calendar.getInstance();
               cal.add( Calendar.DAY_OF_MONTH, -150 );
               begDate2 = cal.getTime();
               fileDate2 = StringUtils.formatDateToString( begDate2, "MM/dd/yyyy");
           }
           m_adaptor_id1 = AdaptorRunInfo.saveAdaptorLastUpdatedStatus( CONSTANT_ADAPTOR, ADAPTOR_NAME1, CONSTANT_SUCCESS, -1);
           m_adaptor_id2 = AdaptorRunInfo.saveAdaptorLastUpdatedStatus( CONSTANT_ADAPTOR, ADAPTOR_NAME2, CONSTANT_SUCCESS, -1);

           AdaptorUtils.printHeader("SPIL SORT FTP", CONSTANT_ADAPTOR);

           AdaptorUtils.removeOldFiles(m_dataOutputDir, m_adaptorLogger );

           FTPClient ftp = login( FTP_HOST, PORT, m_username, m_password );
           log( "Successfully logged in to " + FTP_HOST );
           System.out.println( "Successfully logged in to " + FTP_HOST );

           // change the directory to WS_Data_IP5k
           ftp.chdir( SORT_DIR_IP5K );
           log( "Remote directory changed to "+ SORT_DIR_IP5K );
           System.out.println( "Remote directory changed to " + SORT_DIR_IP5K );

            //To Down DownLoad the File To Local System at Specepied path
           downloadSortOneDirFiles(ftp);

            ftp.chdir("../");
            System.out.println("Remote directory changed to Root Directory ");
           log("Remote directory changed to Root Directory ");

           // change the directory to WS_Data_IP5k
           ftp.chdir(SORT_DIR_IP3K);
           log("Remote directory changed to " + SORT_DIR_IP3K);
           System.out.println("Remote directory changed to " + SORT_DIR_IP3K);

           //To Down DownLoad the File To Local System at Specepied path
           downloadSortTwoDirFiles(ftp);

           // Log out
           logout(ftp);
           log("\nSuccessfully logged out from SPIL Sort Ftp Site");
           System.out.println("\nSuccessfully logged out from  SPIL Sort FTP Site");

       }
       catch ( Exception e )
       {
           throw e;
       }
   }

   private FTPClient login( String host, int port, String m_username, String m_password ) throws Exception
   {
       FTPClient ftp = new FTPClient( host, port );
       ftp.login( m_username, m_password );
       ftp.debugResponses( false );
       ftp.setType( FTPTransferType.BINARY );
       // active does not allows me connect to ftp site even any proxy lies in path.
       ftp.setConnectMode( FTPConnectMode.PASV );
       return ftp;
   }

    private void downloadSortOneDirFiles(FTPClient ftp) throws Exception
    {
        String[] listings = ftp.dir();

        if ((listings == null) || (listings.length == 0))
        {
            return;
        }

        byte[] buf = null;
        FileOutputStream fileOutputStream = null;
        String tempFileName = null;

        try
        {
            java.util.Date maxDate = null;
            java.util.Date tempmaxDate = null;

            System.out.println("\tDownloading Wip Standard files....");


            // Downloading all the vendor files whose date greater than or equal to the
            for (int i = 0; i < listings.length; i++)
            {
                if ( listings[i].endsWith("MAP") && listings[i].indexOf("before") == -1 && listings[i].indexOf("resorted") == -1)
                {
                    java.util.Date date1 = StringUtils.format(fileDate1, "MM/dd/yyyy");
                    java.util.Date date2 = ftp.modtime(listings[i]);

                    if (date2.compareTo(date1) >= 0)
                    {
                        maxDate = date2;
                        if (tempmaxDate == null)
                        {
                            tempmaxDate = maxDate;
                        }
                        else
                        {
                            if (maxDate.compareTo(tempmaxDate) > 0)
                            {
                                tempmaxDate = maxDate;
                            }
                        }
                        tempFileName = listings[i];
                    }
                }
                if (fileDate1 != null && tempFileName != null)
                {
                    log("\ndownloading file " + tempFileName + " to " + m_dataOutputDir + " directory... ");
                     if ( m_adaptor_id1 > 0 )
                    {
                        AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id1 , tempFileName, FILE_EXTN_TXT, StringUtils.formatDateToString(ftp.modtime(tempFileName), "MM/dd/yyyy HH:mm:ss" ) ) ;
                    }
                    buf = ftp.get(tempFileName);

                    int tempLength = tempFileName.lastIndexOf('.');
                    tempFileName = tempFileName.substring(0, tempLength);
                    tempFileName = FILE_NAME_SORT_WIP + "_" + tempFileName + "_" + AdaptorUtils.getTimeAsString() + FILE_EXTN;

                    fileOutputStream = new FileOutputStream(m_dataOutputDir + "/" + tempFileName, false);
                    fileOutputStream.write(buf);
                    fileOutputStream.flush();
                    tempFileName = null;
                }
            }
            if (tempmaxDate != null)
            {
                //To Save the Last Modified date from ftp server
                String maxfileDate = StringUtils.formatDateToString(tempmaxDate, "MM/dd/yyyy");
                log("maxfileDate = " + maxfileDate);
                AdaptorRunInfo.updateLastRunFileDate( m_adaptor_id1 , maxfileDate );
            }

        }
        catch (Exception e)
        {
            log("Exception while downloading......... " + e);
            throw e;
        }
        finally
        {
            if (fileOutputStream != null)
            {
                try
                {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }
                catch (IOException ignore)
                {
                    System.out.println("ignore = " + ignore);
                }
            }
        }
    }
    /**
     *
      * @param ftp
     * @throws Exception
     */
   private void downloadSortTwoDirFiles( FTPClient ftp ) throws Exception
   {
       String[] listings = ftp.dir();

       if ( ( listings == null ) || ( listings.length == 0 ) )
       {
           return;
       }

       byte[] buf                          = null;
       FileOutputStream fileOutputStream   = null;
       String           tempFileName       = null;
       try
       {
           java.util.Date maxDate       = null;
           java.util.Date tempmaxDate   = null;

           System.out.println( "\tDownloading Wip Standard files...." );

           // Downloading all the vendor files whose date greater than or equal to the
           for (int i = 0; i < listings.length; i++)
           {
               if (listings[i].endsWith("MAP"))
               {
                   java.util.Date date1 = StringUtils.format( fileDate2, "MM/dd/yyyy" );
                   java.util.Date date2 = ftp.modtime( listings[i] );
                  
                    if ( date2.compareTo( date1 ) >= 0 )
                    {
                        maxDate = date2;
                        if ( tempmaxDate == null )
                        {
                            tempmaxDate = maxDate;
                        }
                        else
                        {
                            if ( maxDate.compareTo( tempmaxDate ) > 0 )
                            {
                                tempmaxDate = maxDate;
                            }
                        }
                        tempFileName = listings[i];
                    }
               }
               if ( fileDate2 != null &&  tempFileName != null )
               {
                   log( "\ndownloading file " + tempFileName + " to " + m_dataOutputDir + " directory... " );
                    if ( m_adaptor_id2 > 0 )
                    {
                        AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id2 , tempFileName, FILE_EXTN_TXT, StringUtils.formatDateToString(ftp.modtime(tempFileName), "MM/dd/yyyy HH:mm:ss" ) ) ;
                    }
                   buf = ftp.get( tempFileName );

                   int tempLength = tempFileName.lastIndexOf('.') ;
                   tempFileName = tempFileName.substring( 0, tempLength );
                   //tempFileName = tempFileName.substring(tempFileName.indexOf('#') + 1 , tempFileName.indexOf('.') );
                   tempFileName = FILE_NAME_SORT_WIP +"_" + tempFileName  + "_" + AdaptorUtils.getTimeAsString() + FILE_EXTN;

                   fileOutputStream = new FileOutputStream( m_dataOutputDir + "/" + tempFileName, false );
                   fileOutputStream.write( buf );
                   fileOutputStream.flush();
                   tempFileName = null;
                }
           }
           if ( tempmaxDate != null )
            {
                //To Save the Last Modified date from ftp server
                String maxfileDate = StringUtils.formatDateToString( tempmaxDate,"MM/dd/yyyy");
                log( "maxfileDate = " + maxfileDate );
                AdaptorRunInfo.updateLastRunFileDate( m_adaptor_id2 , maxfileDate );
            }

       }
       catch ( Exception e )
       {
           log( "Exception while downloading......... " + e );
           throw e;
       }
       finally
       {
           if ( fileOutputStream != null )
           {
               try
               {
                   fileOutputStream.flush();
                   fileOutputStream.close();
               }
               catch ( IOException ignore )
               {
                   System.out.println("ignore = " + ignore);
               }
           }
       }
   }

   private void logout( FTPClient ftp ) throws Exception
   {
       if ( ftp == null )
       {
           return;
       }
       try
       {
           ftp.quit();
       }
       catch ( Exception ignore )
       {
           System.out.println( "Exception Occuered While Logging Out From SPIL Sort FTP Site" + ignore );
           throw ignore;
       }
       ftp = null;
   }

   /**
    *
    * @param message
    */
   private void log(String message)
   {
       if (message == null) return;

       if (m_adaptorLogger != null)
       {
           synchronized (m_adaptorLogger)
           {
               m_adaptorLogger.logDebug(message + LINE_SEPARATOR);
           }
       }
       else
       {
           System.out.println(message);
       }
   }
}
